<template>
  <div class="box">
    <div class="header">
      <div class="search">
        <el-input
          v-model.number="search"
          size="small"
          placeholder="查询请输入公寓号"
        />
        <el-button type="primary" :icon="Plus" @click="showDialog"
          >添加</el-button
        >
      </div>
    </div>
    <!-- 表单 -->
    <el-table 
      :data="filterTableData" 
      border
      :default-sort="{ prop: 'floorNum', order: 'ascending' }"
      style="width: 100%"
    >
      <el-table-column
        align="center"
        v-for="(name, key) in apartment"
        :key="key"
        :prop="key"
        :label="name"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <!-- 编辑 -->
          <el-button
            type="primary"
            size="small"
            :icon="Edit"
            @click="handleEdit(scope.$index, scope.row)"
          />
          <!-- 删除 -->
          <el-button
            size="small"
            type="danger"
            :icon="Delete"
            @click="handleDelete(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      small
      background
      layout="prev, pager, next, jumper"
      :total="tableData.length"
      :page-size="pageSize"
      @current-change="currentChange"
    />
    <!-- 添加弹出框 -->
    <el-dialog v-model="dialogFormVisible" title="添加公寓">
      <el-form :model="form" ref="ruleFormRef" :rules="rules">
        <el-form-item
          label="公寓号："
          prop="floorNum"
          :label-width="formLabelWidth"
        >
          <el-input v-model.number="form.floorNum" placeholder="请输入公寓号" />
        </el-form-item>
        <el-form-item
          label="公寓名："
          prop="name"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.name" placeholder="请输入公寓名" />
        </el-form-item>
        <el-form-item label="楼层数：" :label-width="formLabelWidth">
          <el-input-number v-model.number="form.layer" :min="1" :max="6" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit(ruleFormRef)">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, toRaw } from "vue";
import { Search, Edit, Delete, Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import {
  getApartment,
  addApartment,
  updateApartment,
  deleteApartment,
} from "@/http/apartment";
import { deleteFun, addUpdateFun } from '@/hooks/curd'

const search = ref("");
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const addUpdate = ref("add");
const ruleFormRef = ref();
// 每页显示条目个数
const pageSize = ref(10);
// 当前页数
const currentPage = ref(1);

// 表单验证
const validatePass = (rule, value, callback) => {
  const reg = /^[1-9][0-9]{0,1}$/;
  if (reg.test(value)) {
    callback();
  } else {
    callback(new Error("请输入2位数字以内的公寓号"));
  }
};
const validatePass2 = (rule, value, callback) => {
  const reg = /^(?:[\u4e00-\u9fa5·]{2,16})$/;
  if (reg.test(value)) {
    callback();
  } else {
    callback(new Error("请输中文公寓名"));
  }
};
const rules = reactive({
  floorNum: [{ validator: validatePass, trigger: "blur" }],
  name: [{ validator: validatePass2, trigger: "blur" }],
});
// 表头
const apartment = {
  floorNum: "公寓号",
  name: "公寓名",
  layer: "楼层数",
};
// 表格列表数据
const tableData = ref([]);
// 表单数据
const form = ref({
  floorNum: "",
  name: "",
  layer: 1,
});

// 异步请求获取公寓数据
const getApartmentData = async () => {
  const data = await getApartment();
  tableData.value = data;
};
getApartmentData();

// 筛选展示数据
const filterTableData = computed(() => {
    // 开始截取的索引
    const startIndex = (currentPage.value - 1) * pageSize.value;
    // 结束截止的索引
    const endIndex = currentPage.value * pageSize.value;
    const pagData = tableData.value.slice(startIndex, endIndex);
    const searchData = tableData.value.filter((data) => data.floorNum === search.value)
    return search.value ? searchData : pagData;
  }
);
// 显示dialog
const showDialog = () => {
  form.value = { floorNum: "", name: "", layer: 1 };
  addUpdate.value = "add";
  dialogFormVisible.value = true;
};
// 提交
const onSubmit = addUpdateFun(
  form, 
  addUpdate, 
  addApartment, 
  updateApartment, 
  getApartmentData, 
  dialogFormVisible
)
// 编辑更新
const handleEdit = (index, row) => {
  dialogFormVisible.value = true;
  addUpdate.value = "update";
  form.value = {...row};
};
// 删除
const handleDelete = deleteFun('公寓', deleteApartment, getApartmentData)
// currentChange 页数改变时触发
const currentChange = (val) => {
  currentPage.value = val;
}
</script>

<style scoped lang='scss'>
:deep(.el-input__inner) {
  margin-right: 10px;
  width: 200px;
  height: 35px;
}
:deep(.el-table th.el-table__cell) {
  background-color: #f5f5f5;
}
:deep(.el-pagination) {
  margin-top: 15px;
  justify-content: center;
}
.box {
  padding: 0 15px;
  .header {
    display: flex;
    padding-right: 20px;
    height: 60px;
    align-items: center;
    justify-content: space-between;
    .search {
      display: flex;
      align-items: center;
    }
  }
}
.el-button--text {
  margin-right: 15px;
}
:deep(.el-input-number) {
  width: 200px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>